package com.iraeta.service.sys.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iraeta.entity.PermissionType;
import com.iraeta.entity.Role;
import com.iraeta.entity.RolePermission;
import com.iraeta.entity.UserRole;
import com.iraeta.mapper.sys.RoleMapper;
import com.iraeta.mapper.sys.UserMapper;
import com.iraeta.service.sys.IRoleService;
import com.iraeta.uitl.Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    UserMapper userMapper;

    @Transactional
    @Override
    public void addRole(Role role) {
        baseMapper.insert(role);
        RolePermission rolePermission = new RolePermission(role.getId(), PermissionType.pingTaiLogin);
        baseMapper.insertRolePermission(rolePermission);
    }

    @Override
    public List<Role> getRoleByName(String roleName) {
        QueryWrapper<Role> qw = new QueryWrapper<>();
        qw.gt("id", 0);
        if(StrUtil.isNotEmpty(roleName)){
            qw.like("roleName", roleName);
        }
        return baseMapper.selectList(qw);
    }

    /*userRole相关 user设置role*/
    @Override
    public List<Role> listAllRole() {
        QueryWrapper<Role> qw = new QueryWrapper<>();
        qw.gt("id", 0);
        return baseMapper.selectList(qw);
    }
    @Override
    public List<Role> listRoleByUserId(int userId) {
        return baseMapper.selectRoleByUserId(userId);
    }

    /*userRole相关， role设置user*/
    @Transactional
    @Override
    public void saveUserRole(int roleId, List<Integer> userList){
        for (Integer userId : userList) {
            if(userMapper.selectByUserRole(userId, roleId) == null){
                UserRole userRole = new UserRole(userId, roleId);
                userMapper.insertUserRole(userRole);
            }
        }
        String userRoleIdStr = Util.parseListToString(userList);
        baseMapper.deleteUserRoleIdStr(roleId, userRoleIdStr);
    }

    /*role permission相关*/
    @Override
    public List<Integer> listRolePermission(int roleId) {
        return baseMapper.selectRolePermission(roleId);
    }
    @Transactional
    @Override
    public void saveRolePermission(int roleId, List<Integer> permissionList) {
        for (Integer permissionId : permissionList) {
            if(baseMapper.selectByRolePermission(roleId, permissionId) == null){
                RolePermission rolePermission = new RolePermission(roleId, permissionId);
                baseMapper.insertRolePermission(rolePermission);
            }
        }
        String rolePermissionIdStr = Util.parseListToString(permissionList);
        baseMapper.deleteRolePermissionIdStr(roleId, rolePermissionIdStr);
    }
}
